﻿
var $dxr = (function (util) {
    var colors = [
        'rgb(46, 199, 201)',//'rgb(192,50,50)',
        'rgb(182, 162, 222)',//'rgb(140,192,50)',
        'rgb(90, 177, 239)',//'rgb(50,192,160)',
        'rgb(255, 185, 128)',//'rgb(80,50,192)',
        'rgb(216, 122, 128)',//'rgb(192,50,100)',
        'rgb(141, 152, 179)',// 'rgb(192,100,50)',
        'rgb(229, 207, 13)',//'rgb(90,192,50)',
        'rgb(151, 181, 82)',// 'rgb(50,170,192)',
        'rgb(149, 112, 109)',//'rgb(130,50,192)',
        'rgb(220, 105, 170)',//'rgb(192,150,50)',
        'rgb(7, 162, 164)',//'rgb(50,192,60)',
        'rgb(154, 127, 209)',//'rgb(50,120,192)',
        'rgb(88, 141, 213)',//'rgb(180,50,192)',
        'rgb(245, 153, 78)',//'rgb(190,192,50)',
        'rgb(192, 80, 80)',//'rgb(50,192,110)',
        'rgb(89, 103, 140)',//'rgb(50,70,192)',
        'rgb(201, 171, 0)',//'rgb(192,50,150)',
    ];

    var getQueryString = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    };

    var buildConfig = function ($scope, config, name, id) {
        var key = id + ':' + name;

        if (config[key] == undefined || config[key] == null || config[key] == '') {
            config[key] = {};
        }

        $scope[name] = config[key];
    };

    var requestCache = {};
    var gettype = Object.prototype.toString;

    function objectToString(obj) {
        var result = "";
        var type = gettype(obj);

        switch (type) {
            case "[object String]":
            case "[object Number]":
            case "[object Boolean]":
                result += obj.toString();
                break;
            case "[object Object]":
                for (var p in obj) {
                    result += objectToString(obj[p]);
                }
                break;
            case "[object Array]":
                for (var i = 0; i < obj.length; i++) {
                    result += objectToString(obj[i]);
                }
                break;
        }

        return result;
    }

    function getCache(url, data, method, callBack) {
        var key = url + method + objectToString(data);

        var model = requestCache[key];

        if (model.loading) {
            model.callBacks.push(callBack);
            return null;
        }

        if (util.isNullOrEmpty(model))
            return null;

        return model.data;
    }

    function setCache(url, data, method, model) {
        var key = url + method + objectToString(data);
        requestCache[key] = {
            time: new Date(),
            data: model
        };
    }

    var cacheInterval = setInterval(function () {

        for (var p in requestCache) {
            var model = requestCache[p];

            if (new Date() - model.time > 600000)
                delete requestCache[p];
        }

    }, 1000 * 60 * 5);

    function alert(title, type, msg) {
        title = util.isNullOrEmpty(title) ? "消息" : title;

        if (type === "ok")
            type = "green";
        else if (type === "error")
            type = "red";
        else if (type === "warn")
            type = "yelow";
        else
            type = "";

        var dom = "";
        dom += '<div class="ui mini modal">';
        dom += '    <div class="header">';
        dom += title;
        dom += '    <i class="close icon" style="cursor:pointer;float:right;"></i>';
        dom += '    </div>';
        dom += '    <div class="content">';
        dom += msg;
        dom += '    </div>';
        dom += '    <div class="actions">';
        dom += '        <div class="ui ' + type + ' ok button">OK</div>';
        dom += '    </div>';
        dom += '</div>';

        var elem = $(dom);

        elem.modal({
            onHidden: function () {
                elem.remove();
            },
            onApprove: function () { return true; }
        }).modal('show');

        $(".close.icon", elem).click(function () {
            elem.modal('hide');
        });
    }

    function confirm(title, msg, ok, cancel) {
        title = util.isNullOrEmpty(title) ? "消息" : title;

        var dom = "";
        dom += '<div class="ui mini modal">';
        dom += '    <div class="header">';
        dom += title;
        dom += '    <i class="close icon" style="cursor:pointer;float:right;"></i>';
        dom += '    </div>';
        dom += '    <div class="content">';
        dom += msg;
        dom += '    </div>';
        dom += '    <div class="actions">';
        dom += '        <div class="ui negative button">取消</div>';
        dom += '        <div class="ui positive right labeled icon button">确定<i class="checkmark icon"></i></div>';
        dom += '    </div>';
        dom += '</div>';

        if (cancel)
            cancel = function () { return true; };

        var elem = $(dom);
        elem.modal({
            onHidden: function () {
                elem.remove();
            },
            onDeny: cancel,
            onApprove: ok
        }).modal('show');

        $(".close.icon", elem).click(function () {
            elem.modal('hide');
        });
    }

    var request = function (http, url, data, method, success, error) {
        var executeError = function (type, msg) {
            if (error && typeof (error) == 'function') {
                error(type, msg);
            } else {
                util.alert("", type, msg);
            }
        };

        var userId = getQueryString("UserId");

        if (!util.isNullOrEmpty(userId)) {
            url = url + (url.indexOf("?") >= 0 ? "&" : "?") + "UserId=" + userId;
        }

        http({
            url: url,
            data: data,
            method: method
        }).success(function (data, status, headers) {
            if (data == undefined || data == null || data == '') {
                if (success && typeof (success) == 'function') {
                    success(data, headers('x-paging-index'), headers('x-result-totalCount'));
                }
            } else if (data.ret == 'ok') {
                if (success && typeof (success) == 'function') {
                    success(data.content, headers('x-paging-index'), headers('x-result-totalCount'));
                }
            } else {
                executeError(data.ret, data.msg);
            }
        }).error(function (a, b, c) {
            executeError("error", "请求失败！");
        });
    };

    var getColors = function () {
        return colors;
    }

    util.getQueryString = getQueryString;
    util.buildConfig = buildConfig;
    util.request = request;
    util.getColors = getColors;
    util.getMonthDay = function (year, month) {
        var d = new Date(year, month, 0);
        return d.getDate();
    };
    util.getWeek = function (y, m, d) {
        var now = new Date(y, m - 1, d),
            year = now.getFullYear(),
            month = now.getMonth(),
            days = now.getDate();
        //那一天是那一年中的第多少天
        for (var i = 1; i <= month; i++) {
            days += util.getMonthDay(year, i);
        }

        //那一年第一天是星期几
        var yearFirstDay = new Date(year, 0, 1).getDay() || 7;

        var week = null;
        if (yearFirstDay == 1) {
            week = Math.ceil(days / 7);
        } else {
            days -= (7 - yearFirstDay + 1);
            week = Math.ceil(days / 7) + 1;
        }

        return week;
    };
    util.isNullOrEmpty = function (data) {
        return data == undefined || data == null || data === "";
    };
    util.alert = alert;
    util.confirm = confirm;
    util.cutString = function (str, length) {
        if (str.length > length)
            str = str.substring(0, length - 1) + "...";

        return str;
    };

    return util;

}($dxr || {}));